import axios from 'axios';
import config from '../config'
import router from '@/router'
import {MessagePlugin} from "tdesign-vue-next";

// Base URL for the API
const API_BASE_URL = config.apiBaseUrl; // Update with your actual API base URL

// Create an axios instance with default settings
const apiClient = axios.create({
    baseURL: API_BASE_URL,
    timeout: 180000, // Set a timeout for requests (optional)
    // headers: {
    //     'Content-Type': 'application/json',
    // },
});

// Add an interceptor to include the auth token in requests, except login requests
apiClient.interceptors.request.use(config => {
    // Check if the request URL does not match the login endpoint


    //登录验证 上线放开
    if (!config.url.includes('api.login/index')) {
        console.log('token',localStorage.getItem('authToken'));
        const token = localStorage.getItem('authToken');

        if (token) {
            config.headers.token = token;
        }
    }




    return config;
}, error => {
    return Promise.reject(error);
});

apiClient.interceptors.response.use(response => {
    console.log('API response:', response);
    if (response.data.code === 403) {
        console.log('token 过期');
        MessagePlugin.error("请先登录");
        // 使用 Vue Router 进行页面跳转
        router.push('/login')
        return response;
    }else{
        return response;
    }
   // return response;
}, error => {
    if (error.response && error.response.status === 403) {
        // 使用 Vue Router 进行页面跳转
        if (!config.url.includes('/login')) {
            router.push('/login')
        }
    }
    console.error('API request error:', error);
    return Promise.reject(error);
});

// Common function for GET requests
export const get = (url, params = {}) => {

    return apiClient.get(url, { params })
        .then(response => response)
        .catch(error => {
            console.error('GET request error:', error);
            throw error; // Forward the error for further handling
        });
};

// Common function for POST requests
export const post = (url, data = {}) => {
    return apiClient.post(url, data)
        .then(response => response)
        .catch(error => {
            console.error('POST request error:', error);
            throw error; // Forward the error for further handling
        });
};
